package com.aaa.mq;

import com.aaa.dao.ActivityMapper;
import com.aaa.dao.ApplyDateDao;
import com.aaa.service.ActivityService;
import com.aaa.utils.ActivityUtil;
import com.wsc.entity.Activity;
import com.rabbitmq.client.Channel;
import com.wsc.entity.Inventory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
public class RabbitmqListener {

    @Resource
    ActivityService activityService;

    @Resource
    ActivityUtil activityUtil;

    @Resource
    ActivityMapper activityMapper;

    @Resource
    ApplyDateDao applyDateDao;
    /**
     * @param activity
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = com.aaa.mq.ActivityDeadMqConfig.ACTIVITY_DEAD_START_QUEUE)
    public void startActivity(Activity activity, Message message, Channel channel) throws IOException {
        System.out.println("活动准备开始，活动编号：" + activity.getAid());
        // 是否需要进行设置活动开始
        // 获取数据库中的最新数据信息
        Activity newActivity = activityService.getById(activity.getAid());
        System.out.println(newActivity.getVersion()+"新与旧"+activity.getVersion());
        if (null != newActivity && (newActivity.getVersion().equals(activity.getVersion()))) {
            // 修改活动状态为开始
            System.out.println("活动开始，活动编号：" + activity.getAid());
            activity.setStatus(1);// 设置开始
            activityService.updateById(activity);
            activityUtil.sendMsg(com.aaa.mq.ActivityMqConfig.ACTIVITY_EX, com.aaa.mq.ActivityMqConfig.ACTIVITY_KEY_END, activity, activity.getEnd());
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);// 应答
    }

    @RabbitListener(queues = com.aaa.mq.ActivityDeadMqConfig.ACTIVITY_DEAD_END_QUEUE)
    public void endActivity(Activity activity, Message message, Channel channel) throws IOException {
        System.out.println("活动结束，活动编号：" + activity.getAid());
        // 修改活动状态为开始
        activity.setStatus(2);// 设置开始
        if( activity.getNums() > 0){
            Inventory inventory=new Inventory();
            inventory.setBook(activity.getBid());
            inventory.setSurplus(activity.getNums());
            applyDateDao.update3(inventory);//活动结束，如果书未卖完，就将剩余图书添加到库存中
        }
        activityService.saveOrUpdate(activity);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);// 应答
    }
}
